package com.top.ruizhong.main.video

import android.media.MediaMetadataRetriever
import android.os.Bundle
import android.view.View
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.PagerSnapHelper
import androidx.recyclerview.widget.RecyclerView
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ScreenUtils
import com.blankj.utilcode.util.ToastUtils
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.module.lemlin.mode.ViewModeFragment
import com.module.lemlin.rxhttp.Status
import com.module.lemlin.rxhttp.msg
import com.shuyu.gsyvideoplayer.GSYVideoManager
import com.shuyu.gsyvideoplayer.listener.GSYSampleCallBack
import com.shuyu.gsyvideoplayer.player.IjkPlayerManager
import com.shuyu.gsyvideoplayer.player.PlayerFactory
import com.shuyu.gsyvideoplayer.utils.GSYVideoType
import com.top.ruizhong.R
import com.top.ruizhong.entity.AudioListEntity
import com.top.ruizhong.main.access.CodeFragment
import com.top.ruizhong.mode.vm.VideoViewModel
import kotlinx.android.synthetic.main.activity_test_video.*
import kotlinx.android.synthetic.main.activity_test_video.mSmartRefreshLayout
import tv.danmaku.ijk.media.exo2.Exo2PlayerManager


class VideoFragment : ViewModeFragment<VideoViewModel>() {

    companion object {
        private const val EXTRA_NAME_CATE_ID = "EXTRA_NAME_CATE_ID"
        fun newInstance(cateId: Int): VideoFragment {
            val bundle: Bundle = Bundle().apply {
                putInt(EXTRA_NAME_CATE_ID, cateId)
            }
            return VideoFragment().apply { arguments = bundle }
        }
    }

    //视频列表适配器
    private val mPlayerAdapter: PlayerGSYAdapter = PlayerGSYAdapter()

    //保存当前下标
    private var mCurrentPosition: Int = 0

    //分页器助手
    private lateinit var mSnapHelper: PagerSnapHelper

    //布局管理器
    private lateinit var mLayoutManager: LinearLayoutManager

    //分类id
    private var mCateId: Int = -2

    override val layoutResId: Int
        get() = R.layout.activity_test_video

    override fun viewModel(): VideoViewModel {
        return createViewModel()
    }

    override fun initView() {

        mCateId = arguments?.getInt(EXTRA_NAME_CATE_ID, -2) ?: -2

        //切换播放器内核
        PlayerFactory.setPlayManager(IjkPlayerManager::class.java)
//        GSYVideoType.setShowType(GSYVideoType.SCREEN_TYPE_CUSTOM)
//        GSYVideoType.setScreenScaleRatio(1080f/2129f)


        mSnapHelper = PagerSnapHelper().apply {
            attachToRecyclerView(rvVideoBody)
        }

        rvVideoBody.apply {
            layoutManager = LinearLayoutManager(
                requireContext(), LinearLayoutManager.VERTICAL, (false)
            ).apply {
                mLayoutManager = this
            }
        }.adapter = mPlayerAdapter

        mPlayerAdapter.setOnItemChildClickListener { adapter, view, position ->
            if (view.id == R.id.ivControlsHeads) {

            } else if (view.id == R.id.ivControlsAttention) {

            } else if (view.id == R.id.tvControlsDiscuss) {

            }
        }

        rvVideoBody.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                if (newState != RecyclerView.SCROLL_STATE_IDLE)
                    return
                val view: View = mSnapHelper.findSnapView(mLayoutManager)
                    ?: return
                val position: Int = recyclerView.getChildLayoutPosition(view)
                if (mCurrentPosition != position) {

                    GSYVideoManager.releaseAllVideos()
                    val gsyVideoPlayer: CustomGSYVideoPlayer =
                        mPlayerAdapter.getCustomGSYVideoPlayer(position)
                            ?: return
                    gsyVideoPlayer.startPlayLogic()
                }
                mCurrentPosition = position
            }
        })

        mSmartRefreshLayout.setOnRefreshListener {
            viewModel.videoIndex(mCateId)
        }
        mSmartRefreshLayout.setOnLoadMoreListener {
            viewModel.videoIndex(mCateId, isLoadMore = true)
        }

    }

    override fun initData() {
        mSmartRefreshLayout.autoRefresh()
    }

    override fun initViewMode() {
        viewModel.videoListLiveData.observe(viewLifecycleOwner, Observer { response ->
            if (response.status == Status.FAILURE) {
                mSmartRefreshLayout.finishRefresh(false)
                mSmartRefreshLayout.finishLoadMore(false)
                toast(response.throwable?.msg ?: "未知错误")
            }
            if (response.status != Status.SUCCESS)
                return@Observer
            mSmartRefreshLayout.finishRefresh()
            mSmartRefreshLayout.finishLoadMore()
            response.httpData?.let {
                if (it.loadMore) {
                    mPlayerAdapter.addData(it.data)
                } else {
                    mPlayerAdapter.setList(it.data)
                }
            }
        })
    }

    override fun onPause() {
        super.onPause()
        mPlayerAdapter.getCustomGSYVideoPlayer(mCurrentPosition)?.onVideoPause()
    }

    override fun onResume() {
        super.onResume()
        mPlayerAdapter.getCustomGSYVideoPlayer(mCurrentPosition)?.startPlayLogic()
    }

    override fun onDestroy() {
        super.onDestroy()
        GSYVideoManager.releaseAllVideos()
    }

}